package com.siss.tenancy.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.lang.reflect.Field;

/**
 * Json序列化null值处理
 * 
 * @author yingw
 * @version 1.0
 */
public class JsonNullValueSerializer extends JsonSerializer<Object> {

	@Override
	public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers)
			throws IOException, JsonProcessingException {
		
		JsonStreamContext outputContext = gen.getOutputContext();
		String currentName = outputContext.getCurrentName();
		Object currentValue = outputContext.getCurrentValue();
		Class<? extends Object> class1 = currentValue.getClass();
		try {
			Field declaredField = class1.getDeclaredField(currentName);
			Class<?> type = declaredField.getType();
			if(type == Integer.class){ // Integer类型null值处理为0
				gen.writeNumber(0);
				return;
			}
		} catch (NoSuchFieldException | SecurityException e) {
			e.printStackTrace();
		}
		
		gen.writeString(""); // 其他null值缺省处理为空""
		
	}



}
